package Controllers;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;

import Bean.BeanBook;
import Impl.BookServiceImpl;
import exception.BookNotFoundException;
/**
 * Servlet implementation class BookDetailsController
 */
@Controller
public class BookDetailsController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    private BookServiceImpl bookService;

    @RequestMapping("/bookdetails")
    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	response.setContentType("text/html;charset=UTF-8");  
    	JSONArray arr = new JSONArray();
    	ApplicationContext applicationContext=(ApplicationContext)request.getSession().getServletContext().getAttribute("ctx");
        bookService=(BookServiceImpl)applicationContext.getBean("BookServiceImpl");
        BeanBook bd;
        
        String bookId=request.getParameter("bookId");
		try {
			bd = bookService.getBookDetails(bookId);
			arr.add(bd.toJson());
		} catch (BookNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

//        if (request.getParameter("bookId") != null) {
//            try {
//            	int bookId=Integer.parseInt(request.getParameter("bookId"));
//            	System.out.println(bookId);
//                bd = bookService.getBookDetails(bookId);
//                arr.add(bd.toJson());
//            } catch (BookNotFoundException ex) {
//                throw new ServletException(ex);
//            }
//
//        }
        response.getWriter().append(arr.toJSONString());
//        request.getRequestDispatcher("index/bookdetail.jsp").forward(request,response);
    }
}
